package JVM;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

public class Pipe {
    static class readerThread implements Runnable{

        private PipedReader reader;

        public readerThread(PipedReader reder){
            this.reader=reder;
        }
        @Override
        public void run() {
            System.out.println("this is reader");
            int receive=0;
            while (true) {
                try {
                    while ((receive=reader.read())!=-1){
                        System.out.print((char)receive);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    static class writerThread implements Runnable{

        private PipedWriter writer;

        public writerThread(PipedWriter writer){
            this.writer=writer;
        }

        @Override
        public void run() {
            System.out.println("this is writer");
            try {
                writer.write("hello!");
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        PipedReader reader=new PipedReader();
        PipedWriter writer=new PipedWriter();
        writer.connect(reader);

        new Thread(new readerThread(reader)).start();
        Thread.sleep(1000);
        new Thread(new writerThread((writer))).start();
    }
}
